<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * Class Admin
 * @package app\admin\controller
 * @ControllerAnnotation(title="审核记录管理")
 */
class Records extends AdminController
{
    protected $sort = [
        'create_time' => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Records();
        $this->orders = new \app\admin\model\Orders();
        $this->users = new \app\admin\model\Users();

        $this->assign('getStatusList', $this->model->getStatusList());
    }

    /**
     * @NodeAnotation(title="待审核")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 强行不联表查询，进行where拦截
            foreach ($where as $k => $v){
                if ($v[0] == 'true_name'){
                    $where[$k] = whereHook($v, 'uid', '\app\admin\model\Users','uid');
                }
            }
            $where[] = ['status', '=', 0];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v){
                $list[$k]['true_name'] = $this->users->where('uid', $v['uid'])->value('true_name');
                $state = $this->orders->getStateList()[$v['state']];
                if (!$v['audit_type']){
                    $new_state = $this->orders->getStateList()[$v['new_state']];
                    if ($state <> $new_state){
                        $list[$k]['state'] = $state.' -> '. $new_state;
                    }else{
                        $list[$k]['state'] = $state;
                    }
                    if ($v['add_pay_amount'] > 0){
                        $list[$k]['pay_amount'] = $v['pay_amount'].' + '.$v['add_pay_amount'];
                    }
                }else{
                    $list[$k]['state'] = $state;
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="已审核")
     */
    public function index2()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 强行不联表查询，进行where拦截
            foreach ($where as $k => $v){
                if ($v[0] == 'true_name'){
                    $where[$k] = whereHook($v, 'uid', '\app\admin\model\Users','uid');
                }
            }
            $where[] = ['status', 'in', [1,2]];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v){
                $list[$k]['true_name'] = $this->users->where('uid', $v['uid'])->value('true_name');
                $state = $this->orders->getStateList()[$v['state']];
                if (!$v['audit_type']){
                    $new_state = $this->orders->getStateList()[$v['new_state']];
                    if ($state <> $new_state){
                        $list[$k]['state'] = $state.' -> '. $new_state;
                    }else{
                        $list[$k]['state'] = $state;
                    }
                    if ($v['add_pay_amount'] > 0){
                        $list[$k]['pay_amount'] = $v['pay_amount'].' + '.$v['add_pay_amount'];
                    }
                }else{
                    $list[$k]['state'] = $state;
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="通过")
     */
    public function through()
    {
        $id = $this->request->param($this->model->getPk());
        $res = $this->model->find($id);
        empty($res) && $this->error('记录不存在');
        // 如果是新增
        if ($res['audit_type']){
            unset($res['id']);
            unset($res['create_time']);
            unset($res['update_time']);
            if ($res['pay_amount'] >= $res['total_amount']){
                $res['state'] = 1;
                $res['success_time'] = time();
            }
            // 开启事务
            Db::startTrans();
            try {
                $create = $this->orders->create($res->toArray());
                $this->model->update(['status' => 1, 'order_id' => $create->id],['id' => $id]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('操作失败:'.$e->getMessage());
            }
            $this->success('审核成功');
        }else{
            $order = $this->orders->find($res['order_id']);
            empty($order) && $this->error('订单不存在');
            $new_pay_amount = $order['pay_amount'] + $res['add_pay_amount'];
            if ($new_pay_amount >= $order['total_amount']){
                $data['state'] = 1;
                $data['success_time'] = time();
            }else{
                $data['state'] = $res['new_state'];
            }
            $data['id'] = $order->id;
            $data['pay_amount'] = $new_pay_amount;
            //开启事务
            Db::startTrans();
            try {
                $this->orders->update($data);
                $this->model->update(['status' => 1],['id' => $id]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('操作失败:'.$e->getMessage());
            }
            $this->success('审核成功');
        }
    }

    /**
     * @NodeAnotation(title="驳回")
     */
    public function reject()
    {
        $id = $this->request->param($this->model->getPk());
        $res = $this->model->find($id);
        empty($res) && $this->error('记录不存在');
        if ($this->request->isAjax()){
            try {
                $res->status = 2;
                $res->description = $this->request->param('description','',false);
                $save = $res->save();
            } catch (\Exception $e) {
                $this->error('驳回失败：'.$e->getMessage());
            }
            $save ? $this->success('驳回成功') : $this->error('驳回失败');
        }
        return $this->fetch();
    }

    
}